package cn.smile.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * JwtFilter
 * 对需要校验的资源进行JWT校验
 */
public class JwtFilter extends GenericFilterBean {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //下面两行代码用于解决乱码
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //得到cookie
        final Cookie[] cookies = request.getCookies();
        //JWT Token
        String jwtToken = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //从cookie中得到jwt token
                if ("auth".equals(cookie.getName())) {
                    jwtToken = cookie.getValue();
                    System.out.println("JWT TOKEN:\t" + jwtToken);
                    break;
                }
            }
        }
        //如果token为空直接返回token为空的结果
        if (null == jwtToken) {
            PrintWriter writer = response.getWriter();
            writer.print("Token为空！");
            writer.flush();
            return;
        }
        try {
            //使用Jwt解析器检查签名是否有效
            final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(jwtToken).getBody();
            System.out.println("该JWT面向的主体：" + claims.getSubject());
            System.out.println("自定义的Claims：" + claims.get("id"));
            //将claim添加到请求中
            request.setAttribute("claims", claims);
        } catch (final SignatureException e) {
            PrintWriter writer = response.getWriter();
            writer.print("Token无效！");
            writer.flush();
            return;
        }
        //返回资源
        filterChain.doFilter(request, response);
    }

}
